package com.softeem.idriveserver.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.softeem.idriveserver.dto.Result;
import com.softeem.idriveserver.entity.Image;
import com.softeem.idriveserver.service.ImageService;
import com.softeem.idriveserver.utils.QiniuOssUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Tag(name = "图片管理")
@CrossOrigin
@RestController
public class ImageController {

    @Autowired
    private ImageService imageService;

    @Operation(summary = "图片上传")
    @Parameters({
            @Parameter(name = "files",description = "图片文件",required = true)
    })
    @PostMapping("/image/upload")
    public Result upload(MultipartFile[] files) throws IOException {
        //声明集合存储所有需要上传图片信息
        List<Image> imgs = new ArrayList<>();
        //创建云存储对象
        QiniuOssUtils ossUtils = new QiniuOssUtils();
        for (MultipartFile file : files) {
            //获取源文件名称
            String fname = file.getOriginalFilename();
            //生成随机的字符串（UUID）作为key
            String key = UUID.randomUUID().toString();
            //上传文件并获取服务端返回的URL
            String url = ossUtils.upload(file.getInputStream(),key);
            //获取文件大小
            long size = file.getSize();

            Image img = new Image();
            img.setName(fname);
            img.setUrl(url);
            img.setSize(size);
            //将产生的图片添加到集合
            imgs.add(img);
        }
         //执行保存
        return imageService.saveBatch(imgs) ? Result.ok().setMsg("上传成功") : Result.fail().setMsg("上传失败");
    }

    /**
     * 图片列表分页显示
     */
    @Operation(summary = "图片列表",description = "分页查询图片列表")
    @Parameters({
            @Parameter(name = "page",description = "页码",required = false),
            @Parameter(name = "limit",description = "每页数据条数",required = false)
    })
    @GetMapping("/image/list")
    public Result list(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "5") Integer limit){
        //执行分页查询
        List<Image> list = imageService.list(new Page<Image>(page, limit));
        long count = imageService.count();
        return Result.ok().setData(list).setMsg("查询成功").setCount(count);
    }

    /**
     * 根据id删除图片，同时清理OSS中的图片文件
     */
    @Operation(summary = "删除图片",description = "根据id删除图片")
    @DeleteMapping("/image/{id}")
    public Result delete(@PathVariable Integer id){
        //根据id查询图片信息
        Image img = imageService.getById(id);
        //创建云存储对象
        QiniuOssUtils ossUtils = new QiniuOssUtils();
        //获取图片的存储路径
        String url = img.getUrl();
        //截取图片的key
        String key = url.substring(url.lastIndexOf("/")+1);
        //删除图片
        ossUtils.delete(key);
        //删除数据库中的记录
        return imageService.removeById(id) ? Result.ok().setMsg("删除成功") : Result.fail().setMsg("删除失败");
    }
}
